package com.azt.back.action.product;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.azt.api.pojo.Category;
import com.azt.api.pojo.ProRepository;
import com.azt.api.service.ProCategoryService;
import com.azt.api.service.ProRepositoryService;
import com.azt.model.AjaxJson;
import com.azt.model.easy.EasyTree;
import com.azt.utils.FreemarkerUtils;
import com.azt.utils.RequestUtils;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/category")
public class CategoryAction {

	@Autowired
	private ProCategoryService proCategoryService;

	@Autowired
	private ProRepositoryService proRepositoryService;

	@RequestMapping("/v_list.do")
	public String list(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer pageno) {
		model.put("cateTypes", CategoryType.values());
		return "category/proCategory_list";
	}

	@RequestMapping("/v_addoredit.do")
	public String list(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		return "category/proCategory_edit";
	}

	@RequestMapping(value = "/o_add.do")
	@ResponseBody
	public JSONObject ajaxAdd(HttpServletRequest request, HttpServletResponse response, ModelMap model,
			Category procategory) {
		JSONObject json = new JSONObject();
		try {
			if (procategory.getId() != null && !"".equals(procategory.getId())) {
				json.put("msg", "编辑成功");
				Category oldpc = proCategoryService.getEntityById(procategory.getId());
				oldpc.setCode(procategory.getCode());
				oldpc.setName(procategory.getName());
				oldpc.setCateType(procategory.getCateType());
				oldpc.setUpdatetime(new Date());
				this.proCategoryService.saveOrUpdate(oldpc);
			} else {
				json.put("msg", "新增成功");
				procategory.setCreatetime(new Date());
				this.proCategoryService.saveOrUpdate(procategory);
			}
			json.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", "操作失败");
		}
		return json;
	}

	@RequestMapping("/v_tree.do")
	@ResponseBody
	public List<EasyTree> getCategoryTree(Integer pid) {
		return proCategoryService.getCategorysTreeBack(pid);
	}

	// 品牌管理的 ztree
	@RequestMapping("/v_ztree.do")
	@ResponseBody
	public List<Category> getCategoryZtree(Integer id) {
		List<Category> all = proCategoryService.getAllCategory();
		if (id != null) {
			// 编辑需要带值回显
			List<Category> checkedCategory = proCategoryService.getCheckedCategoryByBrandId(id);
			for (Category cat : all) {
				for (Category ccate : checkedCategory) {
					if (ccate.getId().equals(cat.getId())) {
						cat.setChecked(true);
					}
				}
			}
		}
		return all;
	}

	@RequestMapping("/o_changeParent.do")
	@ResponseBody
	public void changeParent(Integer targetId, Integer sourceId) {
		proCategoryService.changeParent(targetId, sourceId);
	}

	@RequestMapping(value = "/o_del.do")
	@ResponseBody
	public JSONObject ajaxDel(HttpServletRequest request, HttpServletResponse response, ModelMap model, Category pc) {
		JSONObject json = new JSONObject();
		try {
			if (pc.getId() != null && !"".equals(pc.getId())) {
				json.put("msg", "删除成功");
				Category c = proCategoryService.getEntityById(pc.getId());
				proCategoryService.delete(c);
				json.put("success", true);
			} else {
				json.put("msg", "删除失败，记录不存在");
				json.put("success", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", "删除失败");
		}
		return json;
	}

	/**
	 * 进入选择系统的页面
	 *
	 * @author 张栋 2016年7月6日下午4:36:56
	 */
	@RequestMapping("/v_choose_category.do")
	public String v_choose_category(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		// 取最顶层
		String current = RequestUtils.getString(request, "curent");
		if (current != null) {
			if (current.indexOf(",") != -1) {

				// md5secret,
				String md5secret = RequestUtils.getString(request, "attname");

				// 显示的上下级关系
				List<String> mulitys = new ArrayList<>();
				// 所对应的类目id
				List<String> cagegoryids = new ArrayList<>();
				// 对应的顶级类目
				List<String> cagegorytops = new ArrayList<>();

				// 匹配的类目的3级名称
				List<String> firstname = new ArrayList<>();

				String[] split = current.split(",");
				// 类目有限,不单独写方法了,取类目对应的上级的上级的名称
				for (int i = 0; i < split.length; i++) {
					String cateid = split[i];

					// 分析的时候,会根据这个查
					// 判断仓库中有没有
					ProRepository proRepository = proRepositoryService.getRepositoryBymd5AndPcat(md5secret,
							Integer.parseInt(cateid));
					if (proRepository == null) {
						continue;
					}

					cagegoryids.add(cateid);
					StringBuffer sBuffer = new StringBuffer();
					Category entity = proCategoryService.getEntityById(Integer.parseInt(cateid));
					sBuffer.append(entity.getName());
					firstname.add(entity.getName());
					Category proCategory = entity.getProCategory();
					if (proCategory != null) {
						sBuffer.append("---");
						sBuffer.append(proCategory.getName());

						Category proCategory2 = proCategory.getProCategory();
						if (proCategory2 != null) {
							sBuffer.append("---");
							sBuffer.append(proCategory2.getName());

							Category proCategory3 = proCategory2.getProCategory();
							if (proCategory3 != null) {
								sBuffer.append("---");
								sBuffer.append(proCategory2.getName());
								cagegorytops.add(proCategory3.getId() + "");
							} else {
								cagegorytops.add(proCategory2.getId() + "");
							}
						} else {
							cagegorytops.add(proCategory.getId() + "");
						}
					} else {
						cagegorytops.add(cateid);
					}
					mulitys.add(sBuffer.toString());
				}
				model.put("mulitys", mulitys);
				model.put("cagegoryids", cagegoryids);
				model.put("cagegorytops", cagegorytops);
				model.put("firstname", firstname);
				model.put("md5secret", md5secret);
			}
		}

		model.put("current", current == null ? "" : current);
		try {
			updateCategoryTemp(request, true);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "category/temp_pro_choose_ategory";
	}

	/**
	 * 更新类目选择文件,同时更新下类目
	 *
	 * @author 张栋 2016年7月8日上午9:34:30
	 */
	@RequestMapping("/o_update_category_temp.do")
	@ResponseBody
	public AjaxJson o_update_category_temp(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		AjaxJson j = new AjaxJson();
		try {

			updateCategoryTemp(request, false);
		} catch (Exception e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("请联系开发 !");
		}

		return j;
	}

	/**
	 * 更新类目选择文件
	 *
	 * @author 张栋 2016年7月8日上午9:34:49
	 */
	public void updateCategoryTemp(HttpServletRequest request, boolean auto) throws Exception {
		String tempname = "pro_choose_ategory.html";
		String newtempname = "temp_pro_choose_ategory.html";
		String tempath = request.getSession().getServletContext().getRealPath("/WEB-INF/back/category");
		if (!proCategoryService.proCategoryTempAuotCreate(-2)) {
			// 自动状态下,不存在就生成
			File file = new File(tempath + "/" + newtempname);
			if (file.exists()) {
				// 存在则不生成
				return;
			}

		} else {
			// 非自动情况,直接生成
		}

		List<Category> categorys = proCategoryService.getAllCategories();
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("categorys", categorys);
		FreemarkerUtils.createHtml(tempath, tempname, paramMap, newtempname);
	}

	public enum CategoryType {
		CATEGORY(1, "系统名称"), SYSTEMNAME(2, "类别"), PRODUCTNAME(3, "产品名称");

		private Integer index;
		private String name;

		private CategoryType(Integer index, String name) {
			this.index = index;
			this.name = name;
		}

		public Integer getIndex() {
			return index;
		}

		public void setIndex(Integer index) {
			this.index = index;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}
}
